package com.aspire.nm.component.miniServer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.aspire.nm.component.miniServer.config.Config;
import com.aspire.nm.component.miniServer.config.ConfigException;
import com.aspire.nm.component.miniServer.handle.HandlerThread;
import com.aspire.nm.component.miniServer.plugin.Plugins;
import com.aspire.nm.component.miniServer.status.StatusInfo;


public class Server extends Thread{
    
    public StatusInfo statusInfo ;
    public Config config;
    private Plugins plugins = new Plugins();
    
    public Plugins getPlugins() {
        return plugins;
    }
    public void setPlugins(Plugins plugins) {
        this.plugins = plugins;
    }



    public Server(String configPath,Set<String> controllImplClasssNames,Set<String>filterImplClasssNames) throws  ConfigException{
        this(configPath,controllImplClasssNames);
        config.initfilterImplClasssNames(filterImplClasssNames);
        config.getFilterImpls(true);
    }
    public Server(String configPath,Set<String> controllImplClasssNames) throws ConfigException{
        this(configPath);
        config.initControllImplClasssNames(controllImplClasssNames);
        
        statusInfo.init(config.getControllImpls(true), config.getServerPort(),config.getAnnotationValueConfigFile());
        config.initAnnotationConfig();
    }
    private Server(String configPath) throws ConfigException{
        this();
        config = new Config();
        config.initConfigPath(configPath);
        statusInfo = new StatusInfo(config.getServerPort());
    }
    private Server() throws ConfigException{
    }
    
    
    
    
    public void startServer() {
        exec = new ThreadPoolExecutor(config.getCorePoolSize(),config.getMaximumPoolSize(),
                0,TimeUnit.MILLISECONDS, 
                new ArrayBlockingQueue<Runnable>(config.getWorkQueueSize()),
                new ThreadPoolExecutor.AbortPolicy());
        plugins.start();
        start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void shutdownServer(){
        shutdown = true;
        stop = true;
        try {
            new Socket("127.0.0.1",config.getServerPort());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    
    
    
    private ExecutorService exec;
    private ServerSocket serverSocket;
    private boolean stop = true;
    private boolean shutdown = false;
    public void run(){
        while(!shutdown){
            try {
                stop = false;
                serverSocket = new ServerSocket(config.getServerPort());
                
                while (!stop) {
                    Socket socket = serverSocket.accept();
                    
                    if(stop){
                        socket.close();
                        break;
                    }
                    if(!StringUtils.isEmpty(config.getAllowIpsPattern()) && !Pattern.compile(config.getAllowIpsPattern()).
                            matcher(socket.getInetAddress().getHostAddress()).matches()){
                        socket.close();
                        continue;
                    }
                    statusInfo.accecp();
                    
                    HandlerThread handlerThread = new HandlerThread(socket,this);
                    try{
                        exec.execute(handlerThread);
                    }catch(java.util.concurrent.RejectedExecutionException re){
                        handlerThread.resp503();
                        statusInfo.rejectClose();
                    }
                }
                serverSocket.close();
            } catch (IOException e) {
                try {Thread.sleep(1000);} catch (InterruptedException e1) {}
                e.printStackTrace();
            }
        }
        if(exec != null){
            exec.shutdown();
        }
        plugins.release();
    }
}
